package cn.fr4nk.crawler.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public abstract class FailedTaskHandler extends AbstractHandler<FailedTask> {

	private static Log log = LogFactory.getLog(FailedTaskHandler.class);
	private int maxRetryCount = 5;
	
	protected abstract void exceedMaxRetryCount(FailedTask result);

	@Override
	protected void doHandle(FailedTask result) throws Exception {
		log.debug("……………………………………………… 开始错误处理");
		CrawlerTask task = null;
		try {
			task = result.getTask();
			if (null == result || null == task ) {
				throw new NullPointerException("………………………………………………  无效的失败任务： null");
			}
			if (result.getRetryCount() > maxRetryCount) {
				throw new RuntimeException("……………………………………………… 失败任务重试次数超过最大设定值：" + maxRetryCount);
			}
			log.debug("……………………………………………… 重新抓取 -> " + task.getUrl());
			TaskStore.getInstance().addTodo(task); // 重新抓取
			result.increaseRetryCount(); // 线程安全地新增次数
		} catch (NullPointerException e) {
			log.warn(e);
		} catch (Exception e) {
			log.warn(e);
			log.warn("………………………………………………  失败任务持久化到数据库中");
			exceedMaxRetryCount(result);
			// 失败了
			result.setRetryCount(0);
			TaskStore.getInstance().updateFailedTask(result);
		} finally {
			log.debug("……………………………………………… 结束错误处理");
		}

	}

	public int getMaxRetryCount() {
		return maxRetryCount;
	}

	public void setMaxRetryCount(int maxRetryCount) {
		this.maxRetryCount = maxRetryCount;
	}

}
